import { _decorator, Component, Node, Prefab, instantiate } from "cc";
const { ccclass, property } = _decorator;
import { StateBase } from "../Base/StateBase";
import { BulletEnum } from "../Enum/BulletEnum";
import DataManager from "../Runtime/DataManager";
import { BaseBullet } from "../BaseBullet";
@ccclass("MoreBulletState")
export class MoreBulletState extends StateBase<BulletEnum> {
  constructor(prefab: Prefab) {
    super();
    this.prefab = prefab;
    this.player = DataManager.Instance.player;
    this.bulletParent = DataManager.Instance.bulletParent;
  }
  prefab: Prefab;
  player: Node;
  bulletParent: Node | null = null;
  private shootTimer: number = 0;
  private shootInterval: number = 1; // 射击间隔时间
  // 子弹数量
  static bulletNumber: number = 1;
  public get state(): BulletEnum {
    return BulletEnum.More;
  }
  public beforeEnter(): void {
    console.log("进入更多子弹状态前");
  }
  public enter(): void {
    console.log("进入更多子弹状态");
  }
  public exit(): void {}
  public update(deltaTime: number): void {
    // 更新射击计时器
    this.shootTimer += deltaTime;
    if (this.shootTimer >= this.shootInterval) {
      this.shootTimer = 0;
      const isOdd = MoreBulletState.bulletNumber % 2 === 1;
      const middleIndex = Math.floor(MoreBulletState.bulletNumber / 2);

      for (let i = 0; i < MoreBulletState.bulletNumber; i++) {
        const bulletNode = instantiate(this.prefab);
        if (bulletNode) {
          let direction = 0;
          if (isOdd && i === middleIndex) {
            direction = 0; // 奇数时中间子弹直射
          } else {
            // 计算对称的散射角度
            const offset = isOdd
              ? i < middleIndex
                ? i
                : i - middleIndex - 1
              : i < MoreBulletState.bulletNumber / 2
              ? i
              : i - 1;
            direction =
              i < (isOdd ? middleIndex : MoreBulletState.bulletNumber / 2)
                ? -5 - offset * 3
                : 5 + offset * 3;
          }
          bulletNode.getComponent("BaseBullet").direction = direction;
          bulletNode.setPosition(this.player.position);
          bulletNode.setParent(this.bulletParent);
        }
      }
    }
  }
}
